package com.nice.rm.core;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nice.rm.event.EvenType;
import com.nice.rm.event.Event;
import com.nice.rm.event.EventDispatcher;
import com.nice.rm.event.EventHandler;
import com.nice.rm.util.FileUtil;

/**
 * 
 * 异步持久化内存索引
 * 
 * @author cdyf-2015年5月4日
 */
public class PersistentService implements EventHandler {

    public static final String LAST_INDEX_DIR = "last_index";
    private static final Logger log = LoggerFactory.getLogger(PersistentService.class);

    @Override
    public void handle(Event event) {
        PersistentEvent pev = (PersistentEvent) event.message;
        try {
            pev.radWriter.close();
            Directory fDir = FSDirectory.open(Paths.get(pev.oldIndexFile.getPath()));
            IndexWriterConfig cfg = new IndexWriterConfig(pev.analyzer);
            cfg.setOpenMode(OpenMode.CREATE_OR_APPEND);
            IndexWriter fWriter = new IndexWriter(fDir, cfg);
            fWriter.addIndexes(pev.radWriter.getDirectory());
            FileUtil.close(fWriter);
            deleteLogFileWichIndexIsCreated(pev.logFile);
            saveCurrentIndexDirName(pev.oldIndexFile, pev.curIndex);

            Event update = new Event();
            update.message = fDir;
            update.type = EvenType.UPDATE_INDEX;
            EventDispatcher.getInstance().sendEvent(update);
            
        } catch (IOException e) {
            log.error("Persistent index error", e);
        }
    }

    @Override
    public boolean match(EvenType type) {
        return type == EvenType.PERSIST;
    }

    private void deleteLogFileWichIndexIsCreated(File logFile) {
        FileUtil.deleteFile(logFile);
    }

    private void saveCurrentIndexDirName(File indexDir, long curIndex) throws IOException {
        File file = new File(indexDir.getParent(), PersistentService.LAST_INDEX_DIR);
        FileOutputStream fos = new FileOutputStream(file);
        DataOutputStream dos = new DataOutputStream(fos);
        dos.writeLong(curIndex);
        dos.writeLong(System.currentTimeMillis());
        dos.writeBytes(indexDir.getPath());
        dos.write('\n');
        FileUtil.close(fos, dos);
        log.info("save current index file:" + indexDir);
    }
}
